package cn.school.demo.ui.collect

import android.annotation.SuppressLint
import android.graphics.Color
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.school.demo.MyApplication
import cn.school.demo.R
import cn.school.demo.databinding.FragmentCollectBinding
import cn.school.demo.pojo.Collect
import com.blankj.utilcode.util.LogUtils
import com.mylhyl.circledialog.CircleDialog

class CollectFragment : Fragment() {
    private lateinit var binding: FragmentCollectBinding
    private lateinit var viewModel: CollectViewModel

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        MyApplication.systemBarSetting(MyApplication.DARK, requireActivity())
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_collect, container, false)
        viewModel = ViewModelProvider(this).get(CollectViewModel::class.java)
        binding.vw = this
        binding.lifecycleOwner = viewLifecycleOwner
        init()
        return binding.root
    }

    fun gotoBack() =
        MyApplication.goto(R.id.action_Collect_to_My, findNavController(), parentFragmentManager)

    @SuppressLint("NotifyDataSetChanged")
    fun edit() {
        viewModel.updateEdit()
        when (binding.collectFragmentEdit.text.toString()) {
            "编辑" -> {
                binding.apply {
                    collectFragmentEdit.text = "取消"
                    collectFragmentDeleteLayout.visibility = View.VISIBLE
                }
            }
            "取消" -> {
                binding.apply {
                    collectFragmentEdit.text = "编辑"
                    binding.collectFragmentDeleteLayoutDelete.apply {
                        text = "删除"
                        isEnabled = false
                    }
                    collectFragmentDeleteLayout.visibility = View.GONE
                    LogUtils.d("删除收藏！", viewModel.deleteList.toString())
                    if (viewModel.deleteList.size > 0)
                        viewModel.delete().observe(viewLifecycleOwner) {
                            if (it.success) {
                                viewModel.deleteList.clear()
                                viewModel.getCollectListById().observe(viewLifecycleOwner) { list ->
                                    LogUtils.d(list.toString())
                                    viewModel.setCollectList(list)
                                }
                            } else {
                                CircleDialog.Builder().setText(it.message).setNegative("确定", null)
                                    .show(parentFragmentManager)
                            }
                        }
                }
            }
        }
    }

    fun allDelete() {
        if (viewModel.collectList.size == 0 || viewModel.collectList.isNullOrEmpty()) {
            binding.collectFragmentDeleteLayout.isEnabled = false
        } else {
            CircleDialog.Builder().setText("确定删除全部收藏信息吗？")
                .setPositive("确定") {
                    viewModel.deleteList.clear()
                    viewModel.deleteList.addAll(viewModel.collectList)
                    edit()
                }
                .setNegative("取消", null).show(parentFragmentManager)
        }
    }

    fun delete() {
        CircleDialog.Builder().setText("确定删除选择的收藏信息吗？").setPositive("确定") { edit() }
            .setNegative("取消", null).show(parentFragmentManager)
    }

    @SuppressLint("NotifyDataSetChanged")
    fun init() {
        viewModel.getCollectListById().observe(viewLifecycleOwner) {
            //LogUtils.d(it)
            viewModel.setCollectList(it)
        }
        viewModel.isOk.observe(viewLifecycleOwner) {
            //LogUtils.d(viewModel.collectList)
            binding.collectFragmentRecyclerView.apply {
                adapter?.notifyDataSetChanged() ?: let {
                    layoutManager = LinearLayoutManager(requireContext())
                    adapter = CollectAdapter(viewModel.collectList)
                }
            }
            if (viewModel.collectList.size > 0) {
                binding.collectFragmentNoData.visibility = View.GONE
                binding.collectFragmentRecyclerView.visibility = View.VISIBLE
            } else {
                binding.collectFragmentNoData.visibility = View.VISIBLE
                binding.collectFragmentRecyclerView.visibility = View.GONE
            }
        }
        viewModel.isEdit.observe(viewLifecycleOwner) {
            binding.collectFragmentRecyclerView.adapter?.notifyDataSetChanged()
        }
    }

    private inner class CollectHolder(view: View) : RecyclerView.ViewHolder(view),
        View.OnClickListener {
        private lateinit var collect: Collect
        private val textView: TextView = itemView.findViewById(R.id.fragment_collect_item_text)
        private val timeView: TextView = itemView.findViewById(R.id.fragment_collect_item_time)
        private val image: ImageView = itemView.findViewById(R.id.fragment_collect_item_seclct)

        init {
            itemView.setOnClickListener(this)
        }

        @SuppressLint("SetTextI18n")
        fun bind(collect: Collect) {
            this.collect = collect
            textView.text = this.collect.articleName
            timeView.text = this.collect.userCollectionTime
            image.tag = 0
            if (viewModel.isEdit.value!!) {
                image.apply {
                    setBackgroundResource(R.drawable.circle_unselected)
                    visibility = View.VISIBLE
                }
            } else {
                image.apply {
                    setBackgroundResource(R.drawable.circle_unselected)
                    visibility = View.GONE
                }
            }
            image.setOnClickListener {
                if (it.tag == 0) {
                    it.setBackgroundResource(R.drawable.circle_selected)
                    viewModel.addDeleteList(this@CollectHolder.collect, true)
                    it.tag = 1
                } else {
                    it.setBackgroundResource(R.drawable.circle_unselected)
                    viewModel.addDeleteList(this@CollectHolder.collect, false)
                    it.tag = 0
                }
                if (viewModel.deleteList.size > 0)
                    binding.collectFragmentDeleteLayoutDelete.apply {
                        val text = SpannableString("删除(${viewModel.deleteList.size})")
                        text.setSpan(
                            ForegroundColorSpan(Color.parseColor("#000000")),
                            0,
                            2,
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                        text.setSpan(
                            ForegroundColorSpan(Color.parseColor("#ff0000")),
                            2,
                            text.length,
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                        this.text = text
                        isEnabled = true
                    }
                else binding.collectFragmentDeleteLayoutDelete.apply {
                    text = "删除"
                    isEnabled = false
                }
            }

        }

        override fun onClick(v: View?) {
            //发请求给后端获取文章信息
            LogUtils.e("点我去文章界面！")
            viewModel.getArticle(this.collect.articleId).observe(viewLifecycleOwner) {
                MyApplication.apply {
                    navigateThing["ArticleEntity"] = R.id.action_ArticleEntity_to_Collect.toString()
                    article = it
                    goto(
                        R.id.action_Collect_to_ArticleEntity,
                        findNavController(),
                        parentFragmentManager
                    )
                }
            }
        }
    }

    private inner class CollectAdapter(var collectList: MutableList<Collect>) :
        RecyclerView.Adapter<CollectFragment.CollectHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CollectHolder {
            val view = layoutInflater.inflate(R.layout.list_item_collect, parent, false)
            return CollectHolder(view)
        }

        override fun onBindViewHolder(holder: CollectHolder, position: Int) {
            val collect = collectList[position]
            holder.bind(collect)
        }

        override fun getItemCount() = collectList.size

    }

}